package net.zjitc.servlet.cookies;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookAServlet",urlPatterns = "/CookAServlet")
public class CookAServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Cookie[] cookies = request.getCookies();
        boolean flag=true;
        if(cookies==null||cookies.length==0){
            Cookie cookie=new Cookie("name","xijingping");
            cookie.setMaxAge(60*60);
            response.addCookie(cookie);
            writer.write("请求结束，第一次访问");
        }else{
            for (Cookie c: cookies) {
                if(c.getName().equals("name")){
                    flag=false;
                    writer.write("不是第一次访问");
                }
            }
            if(flag){
                Cookie cookie=new Cookie("name","xijingping");
                cookie.setMaxAge(60*60);
                response.addCookie(cookie);
                writer.write("请求结束，第一次访问");
            }
        }
    }
}
